class PubSub {
  constructor() {
    this.subscribers = {};
  }

  // 订阅
  subscriber(event, callback) {
    if (!this.subscribers[event]) {
      this.subscribers[event] = [];
    }
    const token = Math.random();
    this.subscribers[event].push({
      token,
      callback
    });
    return token;
  }

  // 发布
  publisher(event, data) {
    if (!this.subscribers[event]) return;
    const subscribers = this.subscribers[event].filter(item => {
      return item.token !== false;
    });
    subscribers.forEach(item => item && item.callback(data));
    this.subscribers[event] = subscribers.concat(false, ...this.subscribers[event].filter(item => { item === false }));
  }

  // 取消订阅
  unsucscriber(event, token) {
    if (!this.subscribers[event]) return;
    const isExits = this.subscribers[event].find(item => {
      return item && item.token === token;
    })
    if (!isExits) return;
    this.subscribers[event].map(item => {
      if (item && item.token === token) {
        item.token = false;
      }
      return item;
    })
  }
}

export default new PubSub();